package cn.yujiago.shiro.service.impl;

import cn.yujiago.shiro.domain.DeptDO;
import cn.yujiago.shiro.mapper.DepartmentMapper;
import cn.yujiago.shiro.pojo.LayuiTreeNode;
import cn.yujiago.shiro.service.DepartmentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public List<LayuiTreeNode<DeptDO>> getDepartmentTree() {

        List<DeptDO> deptDOS = departmentMapper.selectAll();
        List<LayuiTreeNode<DeptDO>> rootList = new ArrayList<>();
        List<LayuiTreeNode<DeptDO>> nodeList = new ArrayList<>();

        for(DeptDO deptDO : deptDOS){
            LayuiTreeNode<DeptDO> node = new LayuiTreeNode<>();
            node.setId(deptDO.getId());
            node.setParentId(deptDO.getParentId());
            node.setName(deptDO.getName());
            rootList.add(node);
        }

        // 找出父节点
        for (LayuiTreeNode node : rootList){
            if(node.getParentId() != null && node.getParentId() == 0){
                nodeList.add(node);
            }
        }
        // 为父节点添加子菜单，递归调用
        for(LayuiTreeNode node : nodeList){
            node.setChildren(getChild(node.getId(), rootList));
        }

        return nodeList;
    }

    private List<LayuiTreeNode> getChild(Long id, List<LayuiTreeNode<DeptDO>> rootList){
        // 子菜单
        List<LayuiTreeNode> childList = new ArrayList<>();
        for (LayuiTreeNode node : rootList) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (node.getParentId() != null && node.getParentId() != 0) {
                if (node.getParentId().equals(id)) {
                    childList.add(node);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (LayuiTreeNode node : childList) {// 没有url子菜单还有子菜单
            if (node.getParentId() != null && node.getParentId() != 0) {
                // 递归
                node.setChildren(getChild(node.getId(), rootList));
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
